package basic

import (
	"chat/app"
	"chat/app/common"
	"chat/setting"
	"chat/utils"
	"fmt"
	"io"
	"log"
	"net/http"
	"os"
	"strings"
	"time"
)

const (
	fileHost  = "http://192.168.0.3"
	filePath  = "/public/"
	imagePath = "./website/static"
)

func init() {
	if _, err := os.Stat(imagePath); os.IsNotExist(err) {
		os.MkdirAll(imagePath, os.ModePerm)
		os.Chmod(imagePath, os.ModePerm)
	}
}

// Upload 上传文件
func (c *App) Upload() {
	result := UploadLocal(c.Context)
	c.JSON(http.StatusOK, result)
}

// UploadLocal 将文件存储在本地目录下
func UploadLocal(c *app.Context) any {

	data := make(map[string]interface{})
	code := common.SUCCESS

	//获得上传源文件
	srcFile, head, err := c.Request.FormFile("file")
	if err != nil {
		return common.Response(common.ERROR, err.Error(), data)
	}
	srcFilename := head.Filename

	log.Printf("srcFilename: %v", srcFilename)
	isOriginal := c.PostForm("isOriginal")
	log.Printf("isOriginal: %v", isOriginal)

	var filename string
	if isOriginal == "true" {
		// 原始文件名
		filename = srcFilename
	} else {
		// 新建文件名
		suffix := ".png"
		splitMsg := strings.Split(srcFilename, ".")
		if len(splitMsg) > 1 {
			suffix = "." + splitMsg[len(splitMsg)-1]
		}
		filetype := c.Request.FormValue("filetype")
		if len(filetype) > 0 {
			suffix = filetype
		}
		filename = fmt.Sprintf("%d%s%s", time.Now().Unix(), utils.GenRandomStr(32), suffix)
	}

	// 创建文件
	filepath := imagePath + "/" + filename
	dstfile, err := os.Create(filepath)
	if err != nil {
		return common.Response(common.ERROR, err.Error(), data)
	}
	//将源文件拷贝到新文件
	_, err = io.Copy(dstfile, srcFile)
	if err != nil {
		return common.Response(common.ERROR, err.Error(), data)
	}

	data["path"] = filePath + filename
	data["filePath"] = fileHost + ":" + setting.Server.Port + filePath + filename
	result := common.Response(code, common.GetMsg(code), data)
	return result
}
